import { DataTable, Searchbar, ActivityIndicator, Tooltip } from 'react-native-paper';
import React, { useCallback, useEffect, useState } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  ScrollView,
  StyleSheet,
  Pressable,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import { findFightPage } from 'api/combat';
import BaseCol from 'components/BaseCol';
import useDimensions from 'hooks/useDimensions';
import { useFocusEffect } from '@react-navigation/native';
export default ({ navigation }: RootStackScreenProps) => {
  const hp = useDimensions();
  const [loading, setLoading] = useState(false);
  const styles = StyleSheet.create({
    type: {
      fontSize: 22 * hp,
      fontWeight: '500',
    },
    inactive: {
      fontSize: 26 * hp,
      color: ' rgba(0,0,0,0.9)',
      lineHeight: 30 * hp,
    },
    textBg: {
      width: 114 * hp,
      height: 16 * hp,
      borderRadius: 10,
      position: 'absolute',
      top: 28 * hp,
    },
  });
  const getPageList = (
    page: number,
    itemsPerPage: number,
    searchQuery: string,
    inactive: number,
  ) => {
    setItems([]);
    setLoading(true);
    findFightPage({
      page,
      limit: itemsPerPage,
      incidentTypeCode: ['', '10000', '20000'][inactive],
      address: searchQuery,
    }).then(res => {
      setItems(res?.list ?? []);
      setPage(data => ({ ...data, total: res?.total ?? 0 }));
      setLoading(false);
    });
  };
  const [page, setPage] = React.useState<{
    total: number;
    currentPage: number;
  }>({
    total: 0,
    currentPage: 1,
  }),
    [searchQuery, setSearchQuery] = React.useState('');
  const [numberOfItemsPerPageList] = React.useState([5, 10, 15]);
  const [itemsPerPage, onItemsPerPageChange] = React.useState(
    numberOfItemsPerPageList[1],
  );
  const [inactive, setInactive] = useState(0);
  useFocusEffect(
    useCallback(() => {
      getPageList(page.currentPage, itemsPerPage, searchQuery, inactive);
    }, [page.currentPage, itemsPerPage, inactive, searchQuery]),
  );
  const [items, setItems] = React.useState<Api.resBody['作战指挥表'][]>([]);
  const from = (page.currentPage - 1) * itemsPerPage;
  const onChangeSearch = (query: string) => {
    setPage(data => {
      return {
        ...data,
        currentPage: 1,
      };
    });
    setSearchQuery(query);
  };
  const to = Math.min(page.currentPage * itemsPerPage, page.total);

  return (
    <View
      style={{
        flex: 1,
        backgroundColor: '#fff',
      }}>
      <ActivityIndicator
        animating={loading}
        style={{
          position: 'absolute',
          left: '50%',
          top: '50%',
          zIndex: 100,
        }}
        size={'large'}
      />
      <DataTable
        style={{
          marginTop: 52 * hp,
          flex: 1,
        }}>
        <DataTable.Header>
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              flex: 1,
            }}>
            <View style={{ flexDirection: 'row' }}>
              {[
                {
                  label: '全部警情',
                  code: '',
                },
                {
                  label: '火灾扑救',
                  code: '10000',
                },
                {
                  label: '抢险救援',
                  code: '20000',
                },
              ].map((item, index) => {
                return (
                  <Pressable
                    key={item.label}
                    style={{
                      paddingBottom: 10 * hp,
                      paddingTop: 10 * hp,
                    }}
                    onPress={() => {
                      setInactive(index);
                      setPage(data => {
                        return {
                          ...data,
                          currentPage: 1,
                        };
                      });
                    }}>
                    <Text
                      style={[
                        styles.type,
                        inactive === index ? styles.inactive : undefined,
                        {
                          marginRight: 32 * hp,
                        },
                      ]}>
                      {item.label}
                    </Text>
                    {inactive === index && (
                      <LinearGradient
                        colors={[
                          'rgba(10, 89, 247, 0)',
                          'rgba(10, 89, 247, 0.80)',
                        ]}
                        useAngle
                        angle={270}
                        style={styles.textBg}
                      />
                    )}
                  </Pressable>
                );
              })}
            </View>
            <Searchbar
              style={{
                width: 500 * hp,
                transform: [
                  {
                    scale: hp,
                  },
                ],
              }}
              placeholder="输入警情地址"
              onChangeText={onChangeSearch}
              value={searchQuery}
            />
          </View>
        </DataTable.Header>
        <ScrollView
          overScrollMode="always"
          style={{
            flex: 1,
          }}>
          {items.map(item => (
            <DataTable.Row key={item.id}>
              <View
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  flex: 1,
                }}>
                <BaseCol span={6.5}>
                  <Text>{item.id + '作战指挥'}</Text>
                </BaseCol>
                <BaseCol span={4.5}>
                  <Text>{item.createDate}</Text>
                </BaseCol>
                <BaseCol span={2}>
                  <Text> {item.policeDTO?.incidentType ?? ''}</Text>
                </BaseCol>
                <BaseCol span={4}>
                  <Text> {item.policeDTO?.address}</Text>
                </BaseCol>
                <BaseCol span={3}>
                  <Tooltip title={item.policeDTO?.incidentDes ?? ''}>
                    <Text numberOfLines={1} ellipsizeMode="tail">
                      {item.policeDTO?.incidentDes}
                    </Text>
                  </Tooltip>
                </BaseCol>
                <BaseCol span={4} style={{ flexDirection: 'row' }}>
                  <TouchableOpacity
                    style={{
                      flex: 1,
                    }}
                    onPress={() => {                                            
                      navigation.navigate('PoliceMap', {
                        patrolCommandId: item.policeDTO?.patrolCommandId as unknown as string,
                      });
                    }}>
                    <Text
                      style={{
                        color: '#0A59F7',
                        paddingLeft: 15 * hp,
                        paddingRight: 15 * hp,
                        textAlign: 'center',
                      }}>
                      继续部署
                    </Text>
                  </TouchableOpacity>
                  <TouchableOpacity
                    style={{
                      flex: 1,
                    }}
                    onPress={() => {
                      navigation.navigate('fightRecords', {
                        id: item.id + '',
                      });
                    }}>
                    <Text
                      style={{
                        color: '#0A59F7',
                        paddingLeft: 15 * hp,
                        paddingRight: 15 * hp,
                        textAlign: 'center',
                      }}>
                      复盘作战
                    </Text>
                  </TouchableOpacity>
                </BaseCol>
              </View>
            </DataTable.Row>
          ))}
        </ScrollView>
        {!searchQuery && (
          <DataTable.Pagination
            page={page.currentPage}
            numberOfPages={Math.ceil(page.total / itemsPerPage) + 1}
            onPageChange={page => {
              setPage(data => ({
                ...data,
                currentPage: page === 0 ? 1 : page,
              }));
            }}
            label={`${page.total === 0 ? 0 : from + 1}-${to} of ${page.total}`}
            numberOfItemsPerPageList={numberOfItemsPerPageList}
            numberOfItemsPerPage={itemsPerPage}
            onItemsPerPageChange={value => {
              setPage(data => ({
                ...data,
                currentPage: 1,
              }));
              onItemsPerPageChange(value);
            }}
            style={{
              padding: 10,
            }}
            showFastPaginationControls
          />
        )}
      </DataTable>
    </View>
  );
};
